#include <opencv2/legacy/compat.hpp>

#include "BackProjection.h"
#include "../utils/Logger.h"

BackProjection::BackProjection() {
}

BackProjection::~BackProjection() {
}

IplImage* BackProjection::apply(const IplImage* in) {
    Log << "Applying back projection effect." << endl;

    CvHistogram *hist;
    {
        int sizes[] = {50, 50, 50};
        float bRange[] = {0, 255};
        float gRange[] = {0, 255};
        float rRange[] = {0, 255};
        float *ranges[] = {bRange, gRange, rRange};
        hist = cvCreateHist(3, sizes, CV_HIST_ARRAY, ranges);
    }

    IplImage *c1 = cvCreateImage(cvSize(in->width, in->height), in->depth, 1);
    IplImage *c2 = cvCreateImage(cvSize(in->width, in->height), in->depth, 1);
    IplImage *c3 = cvCreateImage(cvSize(in->width, in->height), in->depth, 1);
    IplImage *channels[] = {c1, c2, c3};
    cvSplit(in, c1, c2, c3, NULL);

    cvCalcHist(channels, hist);

    IplImage *out = cvCreateImage(cvSize(in->width, in->height), in->depth, 1);

    cvCalcBackProject(channels, out, hist);

    cvReleaseImage(&c1);
    cvReleaseImage(&c2);
    cvReleaseImage(&c3);

    cvReleaseHist(&hist);

    return out;
}
